function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

function updateCommentCount() {
    console.log("调用了函数")
    // 获取当前评论标签的长度
    var length = $(".comment_list").length
    $(".comment_count").html(length + "条评论")
    $(".comment").html(length)
}

$(function () {

    // 打开登录框
    $('.comment_form_logout').click(function () {
        $('.login_form_con').show();
    })

    // 收藏
    $(".collection").click(function () {
        // 获取新闻id
        var news_id = $(this).attr("new_id")
        var action = "collect"
        var col_data = {"news_id": news_id, "action": action}
        $.ajax({
            url: "/news/news_collect",
            type: "post",
            contentType: "application/json",
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            data: JSON.stringify(col_data),
            success: function (data) {
                if (data.errno == "0") {
                    // 成功收藏
                    // 隐藏收藏按钮
                    console.log("进入判断，隐藏收藏按钮")
                    $(".collection").hide();
                    // 显示取消收藏按钮
                    console.log("显示隐藏按钮")
                    $(".collected").show();
                } else {
                    alert(data.errmsg);
                }
            }
        })

    })

    // 取消收藏
    $(".collected").click(function () {
        var news_id = $(this).attr("new_id")
        var action = "cancel_collect"
        var col_data = {"news_id": news_id, "action": action}
        $.ajax({
            url: "/news/news_collect",
            type: "post",
            contentType: "application/json",
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            data: JSON.stringify(col_data),
            success: function (data) {
                if (data.errno == "0") {
                    // 隐藏取消收藏按钮
                    $(".collected").hide()
                    // 显示按钮
                    $(".collection").show()
                } else {
                    alert(data.errmsg)
                }
            }
        })

    })

    // 评论提交
    $(".comment_sub").click(function (e) {
        var news_id = $(this).attr("new_id")
        var comment_input = $(".comment_input").val();
        var data = {
            "news_id": news_id,
            "comment_input": comment_input
        }
        $.ajax({
            url: "/news/news_comment",
            type: "post",
            contentType: "application/json",
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            data: JSON.stringify(data),
            success: function (data) {
                if (data.errno == "0") {
                    var comment = data.data
                    var comment_html = ""
                    comment_html += '<div class="comment_list">'
                    comment_html += '<div class="person_pic fl">'
                    if (comment.user.avatar_url) {
                        comment_html += '<img src="' + comment.user.avatar_url + '" alt="用户图标">'
                    } else {
                        comment_html += '<img src="../static/news/images/worm.jpg" alt="用户图标">'
                    }
                    comment_html += '</div>'
                    comment_html += '<div class="user_name fl">' + comment.user.nick_name + '</div>'
                    comment_html += '<div class="comment_text fl">'
                    comment_html += comment.content
                    comment_html += '</div>'
                    comment_html += '<div class="comment_time fl">' + comment.create_time + '</div>'

                    comment_html += '<a href="javascript:;" class="comment_up fr" data-commentid="' + comment.id + '" data-newsid="' + comment.news_id + '">赞</a>'
                    comment_html += '<a href="javascript:;" class="comment_reply fr">回复</a>'
                    comment_html += '<form class="reply_form fl">'
                    comment_html += '<textarea class="reply_input"></textarea>'
                    comment_html += '<input type="button" value="回复" class="reply_sub fr" data-commentid="' + comment.id + '" data-newsid="' + news_id + '">'
                    comment_html += '<input type="reset" name="" value="取消" class="reply_cancel fr">'
                    comment_html += '</form>'
                    comment_html += '</div>'

                    // 将新建的评论追加到第一行

                    $(".comment_list_con").prepend(comment_html)
                    // 失去焦点
                    $(".comment_sub").blur()
                    // 清空输入框的内容
                    $(".comment_input").val("")
                    //更新评论条数
                    updateCommentCount()
                } else {
                    alert(data.errmsg)
                }
            }
        })

    })

    $('.comment_list_con').delegate('a,input', 'click', function () {

        var sHandler = $(this).prop('class');

        if (sHandler.indexOf('comment_reply') >= 0) {
            $(this).next().toggle();
        }

        if (sHandler.indexOf('reply_cancel') >= 0) {
            $(this).parent().toggle();
        }

        if (sHandler.indexOf('comment_up') >= 0) {
            var $this = $(this);
            var action = "add"
            var comment_id = $(this).attr("comment_id")
            var new_id = $(this).attr("news_id")
            var like_count = $(this).attr("like_count")
            if (sHandler.indexOf('has_comment_up') >= 0) {
                // 如果当前该评论已经是点赞状态，再次点击会进行到此代码块内，代表要取消点赞
                action = "remove"
            }

            var send_data = {
                "action": action,
                "comment_id": comment_id,
                "news_id": new_id
            }

            $.ajax({

                url: "/news/comment_like",
                type: "post",
                contentType: "application/json",
                headers: {
                    "X-CSRFToken": getCookie("csrf_token")
                },
                data: JSON.stringify(send_data),
                success: function (data) {
                    if (data.errno == "0" && action == "add") {
                        like_int = parseInt(like_count) + 1
                        $this.addClass("has_comment_up")
                    } else if (data.errno == "0" && action == "remove") {
                        like_int = parseInt(like_count) - 1
                        $this.removeClass("has_comment_up")
                    } else {
                        alert(data.errmsg)
                    }
                    // 更新数据
                    $this.attr("like_count", like_int)
                    if (like_int == 0) {
                        $this.html("赞")
                    } else {
                        $this.html(like_int)
                    }
                }

            })

        }

        if (sHandler.indexOf('reply_sub') >= 0) {
            $this = $(this)
            // 获取需要传输的数据
            var parent_id = $(this).attr("comment_id")
            var news_id = $(this).attr("news_id")
            var content = $(".reply_input").val()
            var send_content = {
                "parent_id": parent_id,
                "news_id": news_id,
                "comment_input": content
            }
            if (!content) {
                return alert("请输入内容再试！")
            }
            $.ajax({
                url: "/news/news_comment",
                type: "post",
                contentType: "application/json",
                headers: {
                    "X-CSRFToken": getCookie("csrf_token")
                },
                data: JSON.stringify(send_content),
                success: function (data) {
                    if (data.errno == "0") {
                        var comment = data.data
                        // 拼接内容
                        var comment_html = ""
                        comment_html += '<div class="comment_list">'
                        comment_html += '<div class="person_pic fl">'
                        if (comment.user.avatar_url) {
                            comment_html += '<img src="' + comment.user.avatar_url + '" alt="用户图标">'
                        } else {
                            comment_html += '<img src="../../static/news/images/person01.png" alt="用户图标">'
                        }
                        comment_html += '</div>'
                        comment_html += '<div class="user_name fl">' + comment.user.nick_name + '</div>'
                        comment_html += '<div class="comment_text fl">'
                        comment_html += comment.content
                        comment_html += '</div>'
                        comment_html += '<div class="reply_text_con fl">'
                        comment_html += '<div class="user_name2">' + comment.parent.user.nick_name + '</div>'
                        comment_html += '<div class="reply_text">'
                        comment_html += comment.parent.content
                        comment_html += '</div>'
                        comment_html += '</div>'
                        comment_html += '<div class="comment_time fl">' + comment.create_time + '</div>'

                        comment_html += '<a href="javascript:;" class="comment_up fr" data-commentid="' + comment.id + '" data-newsid="' + comment.news_id + '">赞</a>'
                        comment_html += '<a href="javascript:;" class="comment_reply fr">回复</a>'
                        comment_html += '<form class="reply_form fl">'
                        comment_html += '<textarea class="reply_input"></textarea>'
                        comment_html += '<input type="button" value="回复" class="reply_sub fr" data-commentid="' + comment.id + '" data-newsid="' + news_id + '">'
                        comment_html += '<input type="reset" name="" value="取消" class="reply_cancel fr">'
                        comment_html += '</form>'

                        comment_html += '</div>'
                        //添加一条新的评论到标签里
                        $(".comment_list_con").prepend(comment_html)
                        // 请空输入框
                        $this.prev().val('')
                        // 关闭
                        $this.parent().hide()

                        //更新评论条数
                        updateCommentCount()
                    }
                }
            })

        }
    })

    // 关注当前新闻作者
    $(".focus").click(function () {
        // 获取参数
        var user_id = $(this).attr("new_user_id")

        // 获取当前关注的数量
        var follows = parseInt($(".follows b ").html())
        follows += 1

        var send_data = {
            "user_id": user_id,
            "action": "follow",
        }
        $.ajax({
            url: "/news/followed_user",
            type: "post",
            contentType: "application/json",
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            data: JSON.stringify(send_data),
            success: function (data) {
                if (data.errno == "0") {
                    // 替换模版的关注数
                    console.log(follows)
                    $(".follows b").html(follows)
                    alert(data.errmsg)
                    $(".focus").hide()
                    $(".focused").show()
                } else if (data.errno == "4101") {
                    window.location.href = "/"
                } else {
                    alert(data.errmsg)
                }
            }

        })

    })

    // 取消关注当前新闻作者
    $(".focused").click(function () {
        var new_user_id = $(this).attr("new_user_id")
        // 获取当前粉丝数量
        var count = $(".follows b").html()

        var send_data = {
            user_id: new_user_id,
            action: "unfollow",
        }
        $.ajax({
            url: "/news/followed_user",
            type: "post",
            contentType: "application/json",
            headers: {
                "X-CSRFToken": getCookie("csrf_token")
            },
            data: JSON.stringify(send_data),
            success: function (data) {
                if (data.errno == "0") {
                    count -= 1
                    $(".follows b").html(count)
                    $(".focused").hide()
                    $(".focus").show()
                    alert(data.errmsg)

                } else {
                    alert(data.errmsg)
                }
            }
        })


    })
})

